import hashlib
import uuid
import os
from datetime import datetime
from functools import wraps

from django.core.cache import cache
from django.shortcuts import redirect

from bg.models import *


def encryption_md5(value):
    """
    使用md5加密
    """

    my_md5 = hashlib.md5()
    my_md5.update(value.encode("utf-8"))
    return my_md5.hexdigest()


def do_file_name(file_name):
    """
    处理文件的名字
    比如xx.jpg--->y798hi3rkkjuiiuh3i8shdf.jpg
    """
    return str(uuid.uuid1()) + os.path.splitext(file_name)[-1]


def check_login_bg(func):
    """登录验证：后台"""

    @wraps(func)
    def inner(*args, **kwargs):
        if args[0].session.get("bg_logined"):
            return func(*args, **kwargs)
        else:
            return redirect("/bg/login/")

    return inner

def check_login_ft(func):
    """登录验证：前台"""

    @wraps(func)
    def inner(*args, **kwargs):
        if args[0].session.get("ft_logined"):
            return func(*args, **kwargs)
        else:
            return redirect("/ft/login/")

    return inner
def set_cache_index():
    """设置缓存"""
    # 查询商品类型
    goodstype_list = GoodsType.objects.all()
    # 循环
    for goodstype in goodstype_list:
        # 动态增加属性
        goodstype.new5 = Goods.objects.filter(goodstype=goodstype).order_by("-id")[:5]
    #设置缓存
    cache.set("cache_index",goodstype_list)

def product_order_id():
    """
    生成订单id  uuid+当前时间
    :return: 订单id
    """
    return  str(uuid.uuid1())+'-'+datetime.now().strftime("%Y%m%d%H%M%S")
if __name__ == '__main__':
    print(encryption_md5("12345"))  # e10adc3949ba59abbe56e057f20f883e
    print(do_file_name("xx.jpg"))
